#include <head.h>
#include <iostream>
#include <functional>

#include <workflow/WFFacilities.h>
#include <workflow/WFHttpServer.h>
using std::cout;
using std::endl;
using std::string;


class MuploadServer {
public:
    MuploadServer(unsigned short port)
    : _port(port)
    //, _httpServer(std::bind(&MuploadServer::process, this, std::placeholders::_1))
    , _httpServer([this](WFHttpTask * serverTask){  this->process(serverTask); })
    , _waitGroup(1)
    {}

    void start();
    void stop();

private:
    void process(WFHttpTask * serverTask);
    void init(const string & username);
    void uppart(const string & uploadID, const string & chunkidx);
    void complete(const string & uploadID);

private:
    unsigned short _port;
    WFHttpServer _httpServer;
    WFFacilities::WaitGroup _waitGroup;
};

void MuploadServer::start()
{
    if(_httpServer.start(_port) == 0) {
        _waitGroup.wait();
        stop();
    } else {
        printf("Http Server start failed.\n");
    }
}

void MuploadServer::stop()
{
    _httpServer.stop();
}

void MuploadServer::process(WFHttpTask * serverTask)
{
    printf("MuploadServer::process is running.\n");
    //0. 对任务的状态进行检测
    //1. 解析请求
    auto req = serverTask->get_req();
    string method = req->get_method();
    //uri中一定是有查询词的
    string uri = req->get_request_uri();
    string path = uri.substr(0, uri.find("?"));
    cout << "method: " << method << endl;
    cout << "path: " << path << endl;

    if(method == "POST" && path == "/file/mupload/init") {
        //解析username
        string username;
        init(username);
    } else if(method == "POST" && path == "/file/mupload/uppart") {
        //解析uploadID和chunkidx
        string uploadID;
        string chunkidx;
        uppart(uploadID, chunkidx);
    } else if(method == "GET" && path == "/file/mupload/complete") {
        //解析uploadID
        string uploadID;
        complete(uploadID);
    }
}

void MuploadServer::init(const string & username)
{
    cout << "init is running.\n";
}

void MuploadServer::uppart(const string & uploadID, const string & chunkidx)
{
    cout << "uppart is running.\n";
}

void MuploadServer::complete(const string & uploadID)
{
    cout << "complete is running.\n";
}

void test0()
{
    MuploadServer muploadServer(8888);
    muploadServer.start();

    cout << "test0 exit" << endl;
}


int main()
{
    test0();
    return 0;
}

